﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using LibraryONTrack.dto;

namespace LibraryONTrack.Persistence.DataMappers
{
	class BookMapper : IDataMapper
	{
		private bool _isInitialized = false;
		private int _ordinal_book_id;
		private int _ordinal_title;
		
		private void InitializeMapper(IDataReader reader)
		{
			PopulateOrdinals(reader);
			_isInitialized = true;
		}

		public void PopulateOrdinals(IDataReader reader)
		{
			_ordinal_book_id = reader.GetOrdinal("book_id");
			_ordinal_title = reader.GetOrdinal("title");
		}

		public object GetData(System.Data.IDataReader reader)
		{
			// This is where we define the mapping between the object properties and the 
			// data columns. The convention that should be used is that the object property 
			// names are exactly the same as the column names. However if there is some 
			// compelling reason for the names to be different the mapping can be defined here.

			// We assume the reader has data and is already on the row that contains the data 
			//we need. We don't need to call read. As a general rule, assume that every field must 
			//be null  checked. If a field is null then the nullvalue for that  field has already 
			//been set by the DTO constructor, we don't have to change it. 
			if (!_isInitialized)
			{
				InitializeMapper(reader);
			}


			Book dto = (Book)GetInstance();

			// Now we can load the data
			if (!reader.IsDBNull(_ordinal_book_id))
			{
				dto.BookId = reader.GetInt64(_ordinal_book_id);
			}

			if (!reader.IsDBNull(_ordinal_title))
			{
				dto.Title = reader.GetString(_ordinal_title);
			}

			return dto;
		}
				
		public int GetRecordCount(System.Data.IDataReader reader)
		{
			Object count = reader["RecordCount"];
			return count == null ? 0 : Convert.ToInt32(count);			
		}


		public object GetInstance()
		{
			return new Book();
		}
	}
}
